package com.cd.university.config.security.validate.email;

import com.cd.university.config.security.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;

/**
 * @author 陈栋
 * @create 2021/9/10 13:52
 */
public class DefaultEmailCodeSender implements EmailCodeSender{

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 邮件接收方，可多人
     */
    private String sendTo;

    /**
     * 邮件主题
     */
    private static final String subject = "邮件验证码";

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private SecurityProperties securityProperties;

    @Async
    @Override
    public void send(String email, String code) {
        logger.info("发送邮件的地址为：" + email + "邮件的验证码为：" + code);

        //创建简单邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        //谁发的
        message.setFrom(from);
        //谁要接收
        sendTo = email;
        message.setTo(sendTo);
        //邮件标题
        message.setSubject(subject);
        //邮件内容
        String context = "你好，此次登录的短信验证码为：" + code +"\n" + "验证码"
                + securityProperties.getCode().getEmailCode().getExpireIn()/60+"分钟内有效";
        message.setText(context);
        try {
            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (MailException e) {
            e.printStackTrace();
            logger.warn("邮件发送失败");
        }
    }
}
